<!-- eslint-disable vue/valid-v-for -->
<template>
  <!-- 序列分析组件 -->
  <div class="rule-label">
    <div class="small-head">
      <el-button
        type="primary"
        :icon="showForm ? 'el-icon-minus' : 'el-icon-plus'"
        class="small-head-btn"
        @click="showForm = !showForm"
      />实体行为
    </div>
    <el-form v-show="showForm" v-model="formData" @submit.native.prevent>
      <section class="floor1">
        <span class="floor1_son">最近</span>
        <el-form-item>
          <el-input-number v-model="formData.action.tempTime" :min="0" controls-position="right" />
        </el-form-item>
        <span class="floor1_son">分钟</span>
        <div class="pointer pointer floor1_son">
          <el-button icon="el-icon-circle-plus" type="text" @click="addHappend">添加</el-button>
        </div>
      </section>
      <el-divider />
      <div class="floor3">
        <!-- 第一部分 -->
        <div v-for="(item, index) in formData.action.conditions" :key="index" style="margin-bottom: 30px">
          <!-- 发生部分 -->
          <div class="happend">
            <span v-if="index === 0" class="floor3_son info" style="margin-right: -38px">依次</span>
            <el-form-item class="floor3_son info" style="margin-left: 50px">
              <span :class="index === 0 ? 'no-pointer' : ''" @click="changeHappen(item, index)">{{
                item.happends
              }}</span>
            </el-form-item>
            <div class="number-tips">{{ letters[index] }}</div>
            <el-form-item :prop="item.event">
              <!--              <el-select-->
              <!--                v-model="item.event"-->
              <!--                filterable-->
              <!--                placeholder="请选择"-->
              <!--                style="margin-right: 15px; width: 230px"-->
              <!--                @change="(val) => resetList(val, index)"-->
              <!--              >-->
              <!--                <el-option-->
              <!--                  v-for="i in formData.transferArray.actionList"-->
              <!--                  :key="i.value"-->
              <!--                  :label="i.label"-->
              <!--                  :value="i.value"-->
              <!--                />-->
              <!--              </el-select>-->
              <el-cascader
                v-model="item.event"
                :options="formData.transferArray.actionList"
                :props="{ expandTrigger: 'hover',emitPath:false }"
                @change="(val) => resetList(val, index)"
              />
            </el-form-item>
            <div v-if="item.happends === '发生过'" class="arrsel">
              <span>，且发生次数</span>
              <el-form-item prop="item.arrSel" style="margin: 0 10px">
                <el-select
                  v-model="item.arrSel"
                  filterable
                  placeholder="请选择"
                  style="margin-right: 15px; width: 100px"
                  @change="(val) => changArrsel(val, item)"
                >
                  <el-option label="等于" :value="0" />
                  <el-option label="在区间" :value="1" />
                </el-select>
              </el-form-item>
              <div v-if="item.arrSel === 1" class="arrsel">
                <el-form-item prop="item.times[0]">
                  <el-input-number
                    v-model="item.times[0]"
                    :min="0"
                    style="width: 100px"
                    controls-position="right"
                    @change="(val) => handleChange(val, index)"
                  />
                </el-form-item>
                <span style="margin: 0 10px">到</span>
                <el-form-item prop="item.times[1]">
                  <el-input-number
                    v-model="item.times[1]"
                    :min="0"
                    style="width: 100px"
                    controls-position="right"
                    @change="(val) => handleChange(val, index)"
                  />
                </el-form-item>
                <span style="margin: 0 20px 0 10px">次</span>
              </div>
              <div v-else>
                <el-form-item prop="item.times">
                  <el-input-number v-model="item.times" :min="0" style="width: 100px" controls-position="right" />
                  <span style="margin: 0 20px 0 10px">次</span>
                </el-form-item>
              </div>
            </div>

            <el-button type="text" @click="addSel(index)">+添加筛选 </el-button>
            <i v-if="index > 0" class="el-icon-close" style="margin-left: 10px" @click="removeHappend(index)" />
          </div>
          <!-- 条件部分 -->
          <div class="stepConditions">
            <div class="satisfid-section">
              <div class="satisfid-line">并且满足</div>
              <div class="show-cus-line" />
              <div v-if="item.conditions.length > 1" class="line-components">
                <div class="divider" />
                <el-button class="changeBtn" @click="changeLogic(item)">{{
                  item.relation === 'and' ? '且' : '或'
                }}</el-button>
                <div class="divider" />
              </div>
              <ul class="ul-list">
                <li v-for="(it, idx) in item.conditions" :key="it + idx + 'll'">
                  <el-select
                    v-model="it.field"
                    filterable
                    placeholder="请选择"
                    style="margin-right: 15px; width: 230px"
                    @change="
                      (val) => {
                        confirmActFirst(val, index, idx)
                      }
                    "
                  >
                    <el-option
                      v-for="i in formData.transferArray.actionFirstList[index].list"
                      :label="i.label"
                      :value="i.value"
                    />
                  </el-select>
                  <el-select
                    v-model="it.operator"
                    filterable
                    placeholder="请选择"
                    style="margin-right: 15px; width: 230px"
                    @change="
                      (val) => {
                        confirmActSec(val, index, idx)
                      }
                    "
                  >
                    <el-option
                      v-for="i in formData.transferArray.actionSecondList[index].lists[idx].list"
                      :label="i.label"
                      :value="i.value"
                    />
                  </el-select>
                  <!-- 枚举类型 -->
                  <el-select
                    v-if="it.isEnum === 1 && it.operator!='ref_in' && it.operator!='ref_not_in' && it.useType!='input'"
                    v-model="it.param"
                    filterable
                    :multiple="it.useType != 'normal'"
                    style="width: 300px"
                    clearable
                    @change="handleChangeInput"
                  >
                    <el-option
                      v-for="i in formData.transferArray.actionEnumList[index].lists[idx].list"
                      :label="i.label"
                      :value="i.value"
                    />
                  </el-select>

                  <!-- 相等或者正则      -->
                  <el-input v-else-if="it.useType === 'input'" v-model="it.param" style="width: 300px" @input="handleChangeInput" />
                  <!-- 包含或者不包含 -->

                  <MultipInput
                    v-else-if="it.useType === 'a-select'"
                    :tags="formData.action.conditions[index].conditions[idx].param"
                    style="width: 300px"
                    @emitInput="(val) => emitActionInput(val, index, idx)"
                  />

                  <!-- 时间选择器 -->

                  <div v-else-if="it.useType === 'datetime'" style="display: inline-block">
                    <el-time-picker
                      v-model="it.tempParam1"
                      style="width: 150px"
                      value-format="HH:mm:ss"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                    />
                    至
                    <el-time-picker
                      v-model="it.tempParam2"
                      style="width: 150px"
                      value-format="HH:mm:ss"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                    />
                  </div>
                  <!-- 关联资源表 -->
                  <el-select v-else v-model="it.refResource" filterable style="width: 300px">
                    <el-option v-for="i in formData.transferArray.resourceList" :label="i.label" :value="i.value" />
                  </el-select>

                  <i class="el-icon-close" style="margin-left: 10px" @click="removeConditon(index, idx)" />
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <!-- 属性部分 -->
      <section v-for="(flr, fidx) in formData.action.attr" :key="flr + fidx" class="floor2">
        <div v-if="fidx === 0" style="display: flex; align-items: center">
          <div class="floor2_son info">按属性分组</div>
          <el-tooltip placement="bottom">
            <div slot="content">可按照行为数据的某些属性进行分组，支持多选或不选</div>
            <i class="el-icon-question" />
          </el-tooltip>
        </div>
        <el-form-item :prop="flr.group" :style="{ marginLeft: fidx > 0 ? '110px' : '10px' }">
          <el-select v-model="flr.group" filterable placeholder="请选择" style="margin-right: 15px; width: 150px">
            <el-option v-for="i in formData.transferArray.groupList" :label="i.label" :value="i.value" />
          </el-select>
        </el-form-item>
        <el-button v-if="fidx === 0" type="text" @click="addGroup">+添加分组 </el-button>
        <i v-if="fidx > 0" class="el-icon-close" style="margin-left: 10px" @click="removeGroup(fidx)" />
      </section>
    </el-form>
  </div>
</template>

<script>
import { changeAction } from '@/views/icp/rule/utils/rule'
import MultipInput from './multipInput.vue'
export default {
  components: { MultipInput },
  props: {
    form: {
      type: Object,
      default: () => {
        return {
          time: undefined,
          conditions: []
        }
      }
    }
  },
  data() {
    return {
      continue: true,
      // 表单数据
      formData: this.form,
      // 行为下拉选择
      typeOptions: [
        { label: '序列', value: 'xulie' },
        { label: '2', value: '2' }
      ],
      showForm: true
    }
  },
  computed: {
    // 字母
    letters() {
      const arr = []
      for (var i = 0; i < 26; i++) {
        arr.push(String.fromCharCode(65 + i))
      }
      return arr
    }
  },
  watch: {
    formData: {}
  },
  mounted() {
    this.exportObj()
  },
  methods: {
    handleChangeInput() {
      this.$forceUpdate()
    },
    changArrsel(val, item) {
      if (val === 1) {
        item.times = []
      } else {
        item.times = 0
      }
    },
    // 计数器方法
    handleChange(val, index) {
      const item = this.formData.action.conditions[index]
      if (Array.isArray(item.times) && item.times[1] < item.times[0]) {
        this.$message.warning('区间选择错误')
      }
    },
    // 处理行为第一步数据
    formatting(val, arr, it, typevalue, index, idx) {
      if (val) {
        const types = arr.filter((i) => {
          return i.value === val
        })
        it.isEnum = types[0].isEnum
        it.valueType = types[0].type
        it.type = typevalue

        // 判断是否可枚举
        if (it.isEnum === 0) {
          this.formData.transferArray.actionSecondList[index].lists[idx].list =
            this.formData.transferArray.typeOptions.filter((ii) => {
              return ii.type === it.valueType || ii.value.includes('baseline')
            })
        } else {
          this.formData.transferArray.actionSecondList[index].lists[idx].list =
            this.formData.transferArray.typeOptions.filter((ii) => {
              return ii.type === 'json' || ii.value.includes('baseline')
            })
          it.useType = 'enum'
          // 获取第三个列表值
          this.formData.transferArray.actionEnumList[index].lists[idx].list = types[0].enumList.map((s) => {
            return {
              value: s.dictValue,
              label: s.dictKey,
              propId: s.groupId,
              id: s.id,
              type: s.type
            }
          })
        }
      }
    },
    // 处理第二步数据
    formatActSec(val, it, typevalue,index,idx) {
      if (it.isEnum === 0) {
        if (val === 'equal' || val === 'regex' || val === 'len_gt') {
          it.useType = 'input'
        } else if (val === 'in' || val === 'not_in') {
          it.useType = 'a-select'
        } else if (val === 'in_time_range') {
          it.useType = 'datetime'
        } else {
          it.useType = 'outer'
        }
      } else {
        if (val !== 'equal') {
          it.useType = ''
        } else {
          it.useType = 'normal'
        }
      }
      if(val.includes('baseline')){
          it.useType = 'normal'
          this.formData.transferArray.actionEnumList[index].lists[idx].list=this.formData.transferArray.baselines
        }
    },
    // 修改实体事件
    async resetList(val, index) {
      await changeAction(val, index, this.formData.transferArray)
      this.formData.action.conditions[index].conditions.forEach((item) => {
        item.field = ''
        item.operator = ''
        item.param = undefined
        item.refResource = ''
      })
    },
    // 修改实体行为组第一项值
    confirmActFirst(val, index, idx) {
      const it = this.formData.action.conditions[index].conditions[idx]
      this.formatting(val, this.formData.transferArray.actionFirstList[index].list, it, 'filter', index, idx)
      it.operator = ''
      it.param = undefined
      it.refResource = ''
    },
    // 修改实体行为组第2项值
    confirmActSec(val, index, idx) {
      const it = this.formData.action.conditions[index].conditions[idx]
      this.formatActSec(val, it, 'filter',index,idx)
      if (val === 'in' || val === 'not_in') {
        it.param = []
      } else {
        it.param = ''
      }
      it.refResource = ''
    },
    // 行为多选组件返回的值
    emitActionInput(val, index, idx) {
      this.formData.action.conditions[index].conditions[idx].param = val
    },

    // 修改文字
    changeHappen(data, index) {
      if (index === 0) return
      data.happends = data.happends === '发生过' ? '未发生' : '发生过'
    },
    // 验证添加组
    testGroup() {
      const isFilled = this.formData.action.conditions.every(item => {
        const actionFilled = this.testAction(item.conditions)
        const { arrSel, times } = item
        return actionFilled && times && arrSel + ''
      })
      if (!isFilled) {
        this.$message.warning('请补全实体行为组')
        return false
      } else {
        return true
      }
    },
    // 增加组
    addHappend() {
      const continueIt = this.testGroup()
      if (!continueIt) return
      this.formData.action.conditions.push({
        happends: '发生过',
        event: '',
        arrSel: 0,
        times: undefined,
        conditions: [
          {
            field: '',
            operator: '',
            param: undefined,
            type: '',
            useType: '',
            refResource: ''
          }
        ],
        relation: 'and'
      })
      if (this.formData.action.attr.length < 1) {
        this.formData.action.attr.push({ group: '', groupType: '' })
      }

      this.formData.transferArray.actionFirstList.push({ list: [] })
      this.formData.transferArray.actionSecondList.push({
        lists: [{ list: [] }]
      })
      this.formData.transferArray.actionEnumList.push({
        lists: [{ list: [] }]
      })
    },
    //   更改判断逻辑
    changeLogic(item) {
      item.relation = item.relation === 'and' ? 'or' : 'and'
    },
    // 测试实体行为并且部分是否填全
    testAction(item) {
      return item.every(it => {
        return it.field && it.operator && (it.param?.toString().length || it.refResource || (it.tempParam1 && it.tempParam2))
      })
    },
    //   添加条件
    addSel(index) {
      const isFilled = this.testAction(this.formData.action.conditions[index].conditions)
      if (!isFilled) {
        this.$message.warning('实体行为含有空白项未填全')
        return
      }
      this.formData.action.conditions[index].conditions.push({
        field: '',
        operator: '',
        param: '',
        refResource: ''
      })
      this.formData.transferArray.actionSecondList[index].lists.push({
        list: []
      })
      this.formData.transferArray.actionEnumList[index].lists.push({
        list: []
      })
    },
    testAttr(index) {
      const isFilled = this.formData.action.attr.every(item => item.group || item.groupType)
      if (!isFilled) {
        this.$message.warning('请先选择空白属性')
        return false
      } else {
        return true
      }
    },
    // 添加属性组
    addGroup() {
      const continueIt = this.testAttr()
      if (!continueIt) return
      if (this.formData.action.attr.length > 2) {
        this.$message.warning('不能添加超过3组')
        return
      }
      this.formData.action.attr.push({
        group: '',
        groupType: ''
      })
    },
    // 移除属性组
    removeGroup(index) {
      this.formData.action.attr.splice(index, 1)
      this.formData.transferArray.actionFirstList.splice(index, 1)
      this.formData.transferArray.actionSecondList.splice(index, 1)
      this.formData.transferArray.actionEnumList.splice(index, 1)
    },
    //   删除组
    removeHappend(index) {
      this.formData.action.conditions.splice(index, 1)
      this.formData.transferArray.actionFirstList.splice(index, 1)
      this.formData.transferArray.actionSecondList.splice(index, 1)
      this.formData.transferArray.actionEnumList.splice(index, 1)
      this.exportObj()
    },
    // 移除满足条件
    removeConditon(index, idx) {
      this.formData.action.conditions[index].conditions.splice(idx, 1)
      this.formData.transferArray.actionSecondList[index].lists.splice(idx, 1)
      this.formData.transferArray.actionEnumList[index].lists.splice(idx, 1)
    },
    // 保存表单
    submitLabel() {
      const continueIt = this.testGroup() && this.testAttr()
      if (!continueIt) return
      this.formData.refResource = []
      return new Promise((resolve, reject) => {
        this.formData.action.time = this.formData.action.tempTime + 'm'
        this.formData.action.conditions.forEach((item, index) => {
          item.alias = this.letters[index]
          // 整理params格式
          if (item.param || item.param === 0) {
            if (Array.isArray(item.param)) {
              item.params = item.param
            } else {
              // 非数组格式
              item.params = [item.param]
            }
          }
          // 整合资源列表
          if (item.refResource) {
            this.formData.refResource.push(item.refResource)
          }
          item.conditions.forEach((it) => {
            if (it.refResource) {
              this.formData.refResource.push(it.refResource)
              it.params = [it.refResource]
            } else if (it.tempParam1 && it.tempParam2) {
              it.params = [it.tempParam1 + '-' + it.tempParam2]
              // eslint-disable-next-line brace-style
            }
            // 数组格式
            else {
              if (Array.isArray(it.param)) {
                it.params = it.param
              } else {
                // 非数组格式
                it.params = [it.param]
              }
            }
          })

          if (Array.isArray(item.times) && item.times.length > 1) {
            if (item.times[1] < item.times[0]) {
              this.$message.warning('区间选择错误')
              this.continue = false
            }
          }
        })
        resolve(this.continue)
      })
        .then((res) => {})
        .then((res) => {
          const rule = {
            rule: this.formData
          }

          if (this.continue) {
            return new Promise((resolve, reject) => {
              resolve(rule)
            })
          } else {
            return false
          }
        })
    },
    // 修改传递给desc的值
    exportObj() {
      const obj = {
        behavior_field_data: []
      }
      // 所有的子项目集合

      this.formData.transferArray.attrList.forEach((item) => {
        obj.behavior_field_data.push(`#{${item.label}}`)
      })

      if (this.formData.action.conditions.length > 0) {
        this.formData.action.conditions.forEach((item, index) => {
          this.formData.transferArray.actionFirstList[0].list.forEach((i, idx) => {
            obj.behavior_field_data.push(`#{${this.letters[index]}.${i.name}}`)
            if (JSON.stringify(obj.behavior_field_data).search(`${this.letters[index]}.分析时间段}`) === -1) {
              obj.behavior_field_data.push(`#{${this.letters[index]}.分析时间段}`)
            }
            if (JSON.stringify(obj.behavior_field_data).search(`${this.letters[index]}.聚合值}`) === -1) {
              obj.behavior_field_data.push(`#{${this.letters[index]}.聚合值}`)
            }
          })
        })
      }

      this.$emit('exportObj', obj)
    }
  }
}
</script>

<style lang="scss" scoped>
.rule-label {
  border: 1px solid #e2e2e2;
  padding: 20px;
  width: calc(100% - 20px);
  margin-left: 20px;
  section {
    display: flex;
    margin: 20px 0;
    align-items: center;
  }
  .small-head {
    .small-head-btn {
      text-align: center;
      border-radius: 2px;
      padding: 0;
      border: 1px solid #95989c;
      align-content: center;
      margin-right: 10px;
    }
  }
  .floor1 {
    margin-top: 20px;

    height: 32px;

    .floor1_son {
      height: 32px;
      line-height: 32px;
      margin: 0 8px;
    }
  }
  .floor3 {
    padding-left: 0;
    .happend {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      .floor3_son {
        margin-right: 8px;
        line-height: 32px;
        text-align: center;
      }
      .number-tips {
        width: 24px;
        height: 24px;
        line-height: 20px;
        border-radius: 2px;
        padding: 3px 7px;
        background: #2979ff;
        color: #fff;
        margin-right: 10px;
        text-align: center;
      }
    }
    .stepConditions {
      margin-bottom: 14px;
      padding-left: 40px;
      width: 100%;
      .satisfid-section {
        display: flex;
        .satisfid-line {
          width: 65px;
          display: flex;
          align-items: center;
          color: #95989c;
          margin-right: 10px;
        }
        .show-cus-line {
          width: 2px;
          background-color: #2979ff;
          margin-right: 12px;
        }
        .line-components {
          display: flex;
          flex-direction: column;
          width: 24px;
          .divider {
            margin: 0 auto;
            height: calc(50% - 12px);
            width: 1px;
            background-color: #cfe4fe;
          }
          .changeBtn {
            width: 24px;
            height: 24px;
            text-align: center;
            padding: 0;
            background-color: #cfe4fe;
            color: #2979ff;
          }
        }
        .ul-list {
          width: 100%;
          padding-left: 10px;
          margin: 0;
          & > li {
            list-style: none;
            text-align: left;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  .floor2 {
    padding-left: 36px;

    .floor2_son {
      margin-right: 8px;
      line-height: 32px;
    }
  }
  .info {
    padding: 0 5px;
    height: 32px;
    background: #f0f0f0;
    border-radius: 2px;
    color: #95989c;
  }
  .arrsel {
    display: flex;
    align-items: center;
  }
  .no-pointer {
    cursor: not-allowed;
  }
}
</style>
